import { Injectable } from '@nestjs/common';
import { CreateUserDto } from 'src/dto/create-user.dto';
import { UpdateUserDto } from 'src/dto/update-user.dto';
import { User } from 'src/entity/user.entity';
import * as argon2 from 'argon2';
import { LoggerService } from 'src/common/logger/logger.service';

@Injectable()
export class UserService {
  constructor() {}

  async create(createUserDto: CreateUserDto) {
    let password = await argon2.hash(createUserDto.password);

    return User.save({
      ...createUserDto,
      password,
      isShow: true,
    });
  }

  async findDistributionUser(pageNum: number, pageSize: number, uid: number) {
    const [list, count] = await User.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      where: { inviteId: uid },
    });

    return { list, count };
  }

  async findAll(pageNum: number, pageSize: number, phone: string) {
    let query: any = {};

    if (phone) {
      query.phone = phone;

      const [list, count] = await User.findAndCount({
        skip: (pageNum - 1) * pageSize,
        take: pageSize,
        where: query,
      });

      return { list, count };
    } else {
      const [list, count] = await User.findAndCount({
        skip: (pageNum - 1) * pageSize,
        take: pageSize,
      });
      return { list, count };
    }
  }

  findOne(id: number) {
    return User.findOneBy({ id });
  }

  /**
   * 绑定商家
   * @param uid 当前用户id
   * @param code 邀请码
   * @returns
   */
  async bindParent(uid: number, code: string) {
    let user = await User.findOneBy({ id: uid });
    if (user.inviteId == 4) {
      let parent = await User.findOneBy({ inviteCode: code });
      user.inviteId = parent.id;
      await user.save();
      return { success: true };
    } else {
      return { success: false, reason: '用户已绑定上级' };
    }
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    return User.update(id, { ...updateUserDto });
  }

  async updateUserInfo(uid: number, body: any) {
    let user = await User.findOneBy({ id: uid });

    user.name = body.name;
    user.avatar = body.avatar;
    user.phone = body.phone;

    return user.save();
  }

  remove(id: number) {
    return User.update(id, { deleteTime: new Date() });
  }
}
